package com.sl.plugin.step.selenium.elementexists;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import lombok.SneakyThrows;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

/**
 */
public class SeleniumElementExistsComp extends AbstractProcessComp<WebDriver, WebDriver> implements ProcessCompService {

    public SeleniumElementExistsComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }

    @SneakyThrows
    @Override
    public WebDriver input(WebDriver driver) {

        String cssSelector = meta.getStrAttr("cssSelector");

        Integer retryCount = meta.getIntAttr("retryCount");

        Integer interval = meta.getIntAttr("interval",500);

        int i = 0;
        Boolean eic = false;
        while (i < retryCount) {
            WebElement element = null;
           try {
                element = driver.findElement(By.cssSelector(cssSelector));
           }catch (Exception e){

           }
            if (ObjectUtil.isNotNull(element)) {
                eic =true;
                break;
            }
            Thread.sleep(interval);
            i++;
        }
        if(BooleanUtil.isTrue(eic)){
            return driver;
        }
        return null;
    }

}
